import { login as loginApi, logout } from '@/api/login'
import {getInfo as getInfoApi} from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { defineStore } from 'pinia'
import router from '@/router'
const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      name: '',
      avatar: '',
      dataScopeSecurity: '', // 密级
      roles: [],
      permissions: [],
      userData: {}
    }),
    actions: {
      
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password.trim()
        let code = '';
        let uuid = '';
        return new Promise((resolve, reject) => {
          loginApi(username, password).then(res => {
            setToken(res.data.token)
            this.token = res.data.token
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 登录浏览平台子系统
      loginSubsystem() {
        return new Promise((resolve, reject) => {
          // 调用浏览平台登录接口，获取token
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfoApi().then(res => {
            console.log(res, '获取用户信息');
            
            const user = res.data.user
            this.userData = user;
            if (res.data.roles && res.data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.data.roles
              this.permissions = res.data.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']//默认角色，那么他的权限是？
            }
            this.name = user.userName;
            let dataScopeSecurity = user.dataScopeSecurity ? user.dataScopeSecurity : 0;
            this.dataScopeSecurity = parseInt(dataScopeSecurity)
            this.avatar = '/api' + user.avatar;
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        removeToken()
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            resolve()
          }).catch(error => {
            reject(error)
          }).finally(() => {
            router.replace({ path: '/login' });
          })
        })
      },
      setInfo(data) {
        for (const key in data) {
          this[key] = data[key]
        }
      },
      setAvatar(str){
        this.avatar = '/api' + str;
      },
    }
  })

export default useUserStore
